package com.bjpowernode.springboot.controller;

import com.bjpowernode.springboot.entity.OfficeDocumentBean;
import com.bjpowernode.springboot.entity.PageBean;
import com.bjpowernode.springboot.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 分页控制层
 */
@Controller
@RequestMapping("/do-page")
@SuppressWarnings("all")
public class PageController {

    @Autowired
    private DocumentService documentService;

    /**
     * 向上翻页
     * @return
     */
    @RequestMapping("/do-up-page")
    public ModelAndView upPage(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        int start = Integer.parseInt(request.getParameter("start"));
        int offset = Integer.parseInt(request.getParameter("offset"));
        PageBean pageBean = new PageBean(start, offset); // 创建分页Bean实体
        List<OfficeDocumentBean> officeDocumentBeans = documentService.queryDocumentByPageBean(pageBean);
        int docCount = documentService.countDocuments(); // 总数
        mv.addObject("documentsList",officeDocumentBeans);
        mv.addObject("docCount",docCount);
        mv.setViewName("doc-nav-page");
        return mv;
    }

    /**
     * 向下翻页
     * @return
     */
    @RequestMapping("/do-down-page")
    public ModelAndView downPage(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        int start = Integer.parseInt(request.getParameter("start"));
        int offset = Integer.parseInt(request.getParameter("offset"));
        int docCount = documentService.countDocuments(); // 总数
        if (start + offset > docCount) {
            // 当前页不满offset的时候
            offset = docCount - start + 1; // 实际页面的偏移量
        }
        PageBean pageBean = new PageBean(start, offset); // 创建分页Bean实体
        List<OfficeDocumentBean> officeDocumentBeans = documentService.queryDocumentByPageBean(pageBean);
        mv.addObject("documentsList",officeDocumentBeans);
        mv.addObject("docCount",docCount);
        mv.setViewName("doc-nav-page");
        return mv;
    }
}
